package util;
/**
 *
 * @author zhaoyingxi
 */
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


public class JdbcUtil {
	private static ThreadLocal<Connection>
		conns = new ThreadLocal<Connection>();

	public static Connection getConnection(){
		Connection conn = conns.get();

		if(conn == null) {
			try {
				//
				InputStream is = 
				JdbcUtil.class.getResourceAsStream(
					"/env.properties");
				
				//
				Properties prop = new Properties();
				prop.load(is);			
				Class.forName(prop.getProperty("driver"));
				conn = 
				DriverManager.getConnection(
				  prop.getProperty("url"),
				  prop.getProperty("username"),
				  prop.getProperty("password")
				);
			} catch (Exception e) {
				throw new RuntimeException(
					"can't get connection!", e);
			}
			//
			conns.set(conn);
			return conn;
		} // if end
		//
		return conn;
	}


	public static void closeConnection(){
		Connection conn = getConnection();
		if(conn != null) {
			try {
				conn.close();				
				conns.set(null);
			} catch(SQLException e) {
				e.printStackTrace();
			}
		}
	}
	 //
	public static void closeResource(ResultSet rs,
		Statement stmt){
		if(rs != null) {
			try {
				rs.close();
			} catch(SQLException e) {
				e.printStackTrace();
			}
		}
		if(stmt != null) {
			try {
				stmt.close();
			} catch(SQLException e) {
				e.printStackTrace();
			}
		}
	}
}